<template>
	<view>
		<uni-segmented-control :current="current" :values="items.map((v) => v.title)" @clickItem="onClickItem" style-type="text" active-color="#80b156">
			<uni-icons type="download" size="25" @click="tableToExcel"></uni-icons>
		</uni-segmented-control>
		<view v-show="current==0">
			<h1>{{title}}</h1>
			<block v-for="(item,index) in data" :key="index">
				<text class="title">第{{index+1}}题：{{item.title}}:</text>
				<uni-table border  emptyText="暂无更多数据" >
					<block v-if="item.type">
						<!-- 表头行 -->
						<uni-tr >
							<uni-th align="center">序号</uni-th>
							<uni-th :sortable="true" align="left">内容</uni-th>
						</uni-tr>
						<!-- 表格数据行 -->
						<uni-tr v-for="(title,i) in item.value" :key="i">
							<uni-td>{{i+1}}</uni-td>
							<uni-td>{{title.content}}</uni-td>
						</uni-tr>
					</block>
					<block v-else>
						<!-- 表头行 -->
						<uni-tr >
							<uni-th align="center">选项</uni-th>
							<uni-th :sortable="true" align="left">比例</uni-th>
						</uni-tr>
						<!-- 表格数据行 -->
						<uni-tr v-for="title in item.value" :key="title">
							<uni-td>{{title.optionName}}</uni-td>
							<uni-td>{{title.num}}</uni-td>
						</uni-tr>
					</block>
				
				</uni-table>
				</block>
		</view>
		<view class="box" v-show='current == 1'>
			<uni-collapse>
				<block v-for="(item,index) in StatementData" :key="item">
					<uni-collapse-item :title="'序号:'+(index+1)+'提交时间:'+item.fillInTheTime">
						<view class="header">
							<label>序号:<text style="font-weight: bold;">{{index+1}}</text></label>
							<label>填写时间:<text>{{item.fillInTheTime}}</text></label>
							<label>来源IP:<text>{{item.ip}}</text></label>
							<label>来源渠道:<text>{{item.answerSource}}</text></label>
						</view>
						<view class="card" v-for="(option,i) in item.optionArray" :key="i">
							<view class="content">
								<label>{{i+1}}.{{option.title}}</label>
								<text>{{option.content}}</text>
							</view>
						</view>
					</uni-collapse-item>
				</block>
			</uni-collapse>

		</view>
		<view>{{ successTip }}</view>
		<view v-show="myUrl">
			<view class="mask" @click="closeMask">
				
			</view>
			<view class="share-card">
				<view class="tip">
					请通过此链接进行下载，谢谢
				</view>
				<view class="showUrl">
					<text class="url scrollBar">{{Url}}</text>
					<view class="copy">
						<text @click="copyClick()">复制</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/api/config.js';
	export default {
		data() {
			return {
				formid:"",
				title:"",
				data:"",
				current: 0,	//页面索引
				items: [		//页面类型
					{ title: '统计结果' },
					{ title: '详细数据' }
				],
				StatementData:"",
				successTip: '',
				Url:'',
				myUrl:false
			}
		},
		onLoad:function(option){
			this.formid = option.formid
			this.Url = config.api()+'/pdf/export?formid='+option.formid
			this.title= option.title
			this.$request('/UserAnswer/statistics','GET',{formid:this.formid})
			.then(res=>{
				console.log(res);
				if(res.data.data.length){
					res.data.data.forEach((item,index)=>{
						var temArray = []
						item.value.forEach(j=>{
							temArray.push(JSON.parse(j))
						})
						item.value = temArray
						if(item.value[0].optionName){
							item['type'] = 0
						}else{
							item['type'] = 1
						}
					})
					this.data = res.data.data
				}
			})
			this.$request('/UserAnswer/Statement','GET',{formid:this.formid})
			.then(res=>{
				console.log(res);
				this.StatementData = res.data.data
			})
		},
		methods: {
			closeMask(){
				this.myUrl = false
			},
			onClickItem(e){
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			// 导出EXCEL
			uuid() {
					return 'xxx-xxx-xxx'.replace(/[xy]/g, c => {
						var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
						return v.toString(16)
					})
				},
			
				tableToExcel() {
					if(this.current === 0){
						this.myUrl = true
						return
					}
					// 要导出的json数据
					const jsonData = this.StatementData
					// 列标题
					let worksheet = 'sht1'
					let str = '<tr><td style="text-align: center">序号</td><td style="text-align: center">提交答卷时间</td><td style="text-align: center">来源</td><td style="text-align: center">来自IP</td>'
					let max = this.StatementData[0].optionArray.length
					var maxDatalength = 0
					this.StatementData.forEach((item,index)=>{
						if(item.optionArray.length > max){
							max = item.optionArray.length
							maxDatalength = index
						}
					})
					this.StatementData[maxDatalength].optionArray.forEach(item=>{
						str += `<td style="text-align: center">${item.title}</td>`
					})
					str += "</tr>"
					// 循环遍历，每行加入tr标签，每个单元格加td标签
					for (let i = 0; i < jsonData.length; i++) {
						str += `<tr>
									<td>${i+1 + '\t'}</td>
									<td>${jsonData[i].fillInTheTime + '\t'}</td>
									<td>${jsonData[i].answerSource + '\t'}</td>
									<td>${jsonData[i].ip + '\t'}</td>
								`
						jsonData[i].optionArray.forEach(item=>{
							// 增加\t为了不让表格显示科学计数法或者其他格式
							str += `<td>${item.content + '\t'}</td>`
						})
						str += '</tr>'
					}
					// 下载的表格模板数据
					let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
			xmlns:x="urn:schemas-microsoft-com:office:excel" 
			xmlns="http://www.w3.org/TR/REC-html40">
			<head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
			<x:Name>${worksheet}</x:Name>
			<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
			</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
			</head><body><table>${str}</table></body></html>`
					// 下载模板
					// #ifdef APP-PLUS
					this.appExportFile(template)
					// #endif
					// 下载模板
					// #ifdef MP-WEIXIN
					this.wxExportFile(template)
					// #endif
				},
			
				// 导出文件到手机 fileData:要写入到文件的数据，返回参数为文档路径
				appExportFile(fileData, documentName = '项目Excel文件') {
					// PUBLIC_DOCUMENTS: 程序公用文档目录常量
					plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
						let rootObj = fs.root, fullPath = rootObj.fullPath
						console.log('开始导出数据********')
						// 创建文件夹
						rootObj.getDirectory(documentName, {
							create: true
						}, dirEntry => {
							// 创建文件,防止重名
							let fileName = 'excel' + this.uuid() + '.xlsx'
							dirEntry.getFile(fileName, {
								create: true
							}, fileEntry => {
								fileEntry.createWriter(writer => {
									writer.onwritestart = res => console.log('正在导出')
									//  /storage/emulated/0指的就是系统路径
									let pathStr = fullPath.replace('/storage/emulated/0', '')
									// 成功导出数据
									writer.onwrite = res => {
										// 文件路径
										let filePath = res.target.fileName
										uni.hideLoading()
										setTimeout(() => {
											console.log('成功导出')
											this.successTip = `文件位置：${filePath}`
											
											uni.openDocument({
												filePath,
												success: res => console.log('打开文档成功'),
												fail: err => console.log(err)
											})
										}, 500)
									}
									// 写入内容
									writer.write(fileData)
								}, err => console.log(err.message))
							})
						})
					})
				},
			
				wxExportFile(template, documentName = '项目Excel文件') {
					const fs = wx.getFileSystemManager()
					// 创建文件名字, 防止重名
					let filePath = wx.env.USER_DATA_PATH + '/' + (documentName + this.uuid()) + '.xls'
					fs.writeFile({
						filePath,
						data: template,
						encoding: 'utf8',
						success: res => {
							wx.openDocument({
								filePath,
								success: res => console.log('打开文档成功。文件位置', filePath),
								fail: err => console.log(err)
							})
						},
						fail: err => console.info(err)
					})
				},
				copyClick(){
					if (this.Url) {
						uni.setClipboardData({
							data: this.Url, //当前点击的地址
							success: () => {
								//获取刚复制好的地址到剪切板，
								uni.getClipboardData({
									success: () => {
										uni.showToast({
											title: '复制成功',
											icon:"none"
										})
									}
								});
							}
						});
					}
				}
		}
	}
</script>

<style lang="less" scoped>
.box{
	background-color: #e3e3e3;
}
h1{
	text-align: center;
	font-weight: bold;
	margin-top: 30rpx;
}
.title{
	display: flex;
	font-size: 14px;
	margin: 30rpx;
	font-weight: 500rpx;
}
label{
	display: block;
	font-size: 14px;
	margin-left: 30rpx;
	margin-top:20rpx;
	text{
		position: absolute;
		left: 200rpx;
	}
}
.card{
	width: 100vw;
	height: auto;
	font-size: 14px;
	border-top: 1px solid #cfcfcf;
	.content{
		margin: 30rpx;
		label{
			margin: 10rpx;
		}
		text{
			color: #7d7d7d;
			margin: 10rpx;
		}
	}
}
.mask {
background-color: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 99;
}
.share-card{
	z-index: 999;
	width: 92%;
	background-color: white;
	height: 20vh;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
	border-radius: 10px;
	.showUrl{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 40rpx;
		.url{
			width: 60%;
			font-size: 14px;
			overflow-x: auto;
		}
		.copy{
			width: 18%;
			height: 5vh;
			margin-left: 40rpx;
			border: 1px solid #dfdfdf;
			border-radius: 5px;
			font-size: 14px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #efefef;
			color: #7777a0;
		}
	}
	.tip{
		font-weight: bold;
		text-align: center;
		margin-top: 10rpx;
		border-bottom: 1px solid #d8d8d8;
	}
}
</style>
